package com.tao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tao.config.MyLog;
import com.tao.pojo.User;
import com.tao.pojo.vo.ResponseResult;
import com.tao.pojo.vo.UserVo;
import com.tao.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class CmsUserController {
    @Autowired
    private UserService userService;
    /** 用户列表 用户详情 用户注销 */
    @PostMapping("/list")
    @PreAuthorize("hasAnyAuthority('admin')")
    @MyLog(value = "用户列表")
    public Object list(@RequestBody UserVo user){
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<UserVo> arrayList = new ArrayList<>();
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        Page<User> page = new Page<>(user.getCurrent(),user.getSize());

        lqw.like(!ObjectUtils.isEmpty(user.getUsername()),User::getUsername,user.getUsername());
        lqw.eq(User::getUserType,1);

        Page<User> list = userService.page(page, lqw);

        // 实现将list数组的数据拷贝到arrayList 但User类 换成UserVo类 用strom流方法
        for (User u : list.getRecords()) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(u, userVo); // 使用BeanUtils进行对象属性拷贝
            arrayList.add(userVo);
        }

        map.put("list",arrayList);
        map.put("total",list.getTotal());
        return ResponseResult.success(map);
    }

    // 用户注销
    @MyLog("用户注销")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/remove")
    public Object remove(@RequestBody UserVo user){
        userService.removeById(user.getId());
        return ResponseResult.success(null);
    }
}
